<!---
wangjia 202208
构造供应商属性管理页面
2.将icon进行阿里云上传管理

wangjia：
  实现属性和suppliercase的对应写入、读取功能
  先读取全部attr和全部case，然后进行配置写入，一个attr对应多个cases。

  [add]基于attr列表，将穿梭框控件对于于属性的每一列，通过一对多的方式进行写入，写入后直接进入redis和后台db。
       若之前存在数据的，先全部删除attr对应的产品再进行add。
  [mod]基于attr列表，先读取attrid对应的redis中的集合并渲染到穿梭框，再类似[add]模式进行写入。先全部删除attr对应的产品再add
  [del]解除一条的对应关系，需要全部删除再全部添加

  综上，任何编辑，都是先查询attr对应的产品数据集合，删除db，然后生成新数据，在redis和db中覆盖。

--->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="属性名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入属性名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supplier:attr:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supplier:attr:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supplier:attr:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supplier:attr:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attrList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="属性名称" align="center" prop="name" />
      <el-table-column label="属性类型" align="center" prop="type"  :formatter="typeFormat"/>
      <el-table-column label="属性描述" align="center" prop="subname" />
      <el-table-column label="图标" align="center" prop="iconurl" >
        <template slot-scope="scope">
        <el-popover placement="top-start" trigger="click">
          <a :href="scope.row.iconurl" target="_blank" title="查看图标">
            <img :src="scope.row.iconurl" style="width: 100px;height: 100px">
          </a>
          <img slot="reference" :src="scope.row.iconurl" style="width: 50px;height: 50px; cursor:pointer">
        </el-popover>
       </template>
      </el-table-column>
      <el-table-column label="属性权重值，越小越靠前" align="center" prop="weights" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supplier:attr:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supplier:attr:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleMapping(scope.row)"  
          >配置</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog title=" 配置属性-产品 " :visible.sync=" openConfig "  width="900px" append-to-body>
       <p style="text-align: center; margin: 0 0 20px">{{subTitle}}</p>
          <div style="text-align: center" class="edit_dev">
            <el-transfer
              style="text-align: left; display: inline-block"
              v-model="chooseRole"
              :props="{
                key: 'id',
                label: 'projectTitle'
              }"
              filterable
              :render-content="renderFunc"
              :titles="['未关联', '已关联']"
              :button-texts="['到左边', '到右边']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              @right-check-change="choose"
              target-order="push"
              @change="handleChange"
              :data="caseList">


                  <el-button
                    class="transfer-footer"
                    slot="right-footer"
                    size="mini"
                    @click="handleUp(index)"
                  >上移
                  </el-button>
                  <el-button
                    class="transfer-footer"
                    slot="right-footer"
                    size="mini"
                    @click="handleDown(index)"
                  >下移
                  </el-button>

              
              <el-button class="transfer-footer" slot="right-footer" size="small" @click="saveItem">保存</el-button>
            </el-transfer>
          </div>
    </el-dialog>

    <!-- 添加或修改供应商案例属性对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="属性子标题/描述" prop="subname">
          <el-input v-model="form.subname" placeholder="请输入属性子标题/描述" />
        </el-form-item>
        <el-form-item label="属性类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
              v-for="item in staOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性权重值" prop="weights">
          <el-input v-model="form.weights" placeholder="请输入属性权重值，越小越靠前" />
        </el-form-item>
        <el-form-item label="图标" prop="iconurl">
          <!-- <el-input v-model="form.iconurl" type="textarea" placeholder="请输入内容" /> -->
          <el-upload
                  class="upload-demo"
                  :limit="1"
                  :action="uploadFileUrl"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-success="handleUploadSuccess"
                  :data = "updata"
                  :headers="headers"
                  :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">不超过1Mb</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttr, getAttr, delAttr, addAttr, updateAttr } from "@/api/supplier/attr";
import { getToken } from "@/utils/auth";
import { listFromRds } from '@/api/supplier/case';
import {listCaseAttrLink, deleteAndAddCaseAttrLink } from '@/api/supplier/caseAttrLink';
export default {
  name: "Attr",
  data() {
    return {
      chooseRole: [],
      sort: '',
      item: '',
      index: '',
      attrListAll: [],
      caseList: [], 
      fileList: [],
      subTitle: '',
      attrId: 0,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/uploadFile", // 上传的图片服务器地址
       headers: {
        Authorization: "Bearer " + getToken(),
      },
       uploadObjectUrl: "", // 纯前端预览地址-upload
       uploadOnlineUrl: "", // 后端返回的上传地址-upload
       updata:{"strPath":"icons"},
       options: [
        {
          value: '1',
          label: '主属性'
        }, 
        {
          value: '2',
          label: '小属性'
        }
      ],
      staOptions: [
        {
          value: '1',
          label: '启用'
        }, 
        {
          value: '0',
          label: '禁用'
        }
      ],
      openConfig: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商案例属性表格数据
      attrList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "属性名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "属性类不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getAttrList();
    this.getCaseList();
    this.getList();
  },
  methods: {
    renderFunc(h, option) {
          return <span>{ option.id } - { option.projectTitle }</span>;
      },
    handleChange(value, direction, movedKeys) {
        console.log(value, direction, movedKeys);
      },

    //右侧选中
    choose (value) {
      let self = this
      self.item = value
    },
    //上移
    handleUp (item, index) {
      // item为选中的项，index为对应的index
      let self = this;
      item = self.item;
      console.log(item)
      if (item.length == 1) {
        self.chooseRole.find((val, indexs, arr) => {
          if (val == item) {
            index = indexs;
          }
        });
        if (index == 0) {
          //当选择的项的下标为0
          self.$message("已经移到顶部");
          return;
        }
        // 上移-改变的数组
        let changeItem = JSON.parse(JSON.stringify(self.chooseRole[index - 1]));
        self.chooseRole.splice(index - 1, 1);
        self.chooseRole.splice(index, 0, changeItem);
      } else {
        self.$message.error("只能选择一条数据上移");
        return;
      }

    },

    //下移
    handleDown (item, index) {
      let self = this;
      item = self.item;
      if (item.length == 1) {
        //选中值的下标
        self.chooseRole.find((val, indexs, arr) => {
          if (val == item) {
            index = indexs;
          }
        });

        if (index == self.chooseRole.length - 1) {   // 这里是length-1,因为下标值从0开始
          self.$message("已经移到底部");
          return;
        }
        let changeItem = JSON.parse(JSON.stringify(self.chooseRole[index]));
        self.chooseRole.splice(index, 1);
        self.chooseRole.splice(index + 1, 0, changeItem);
      } else {
        self.$message.error("只能选择一条数据下移");
        return;

      }

    },



    saveItem(value) {
      console.log(this.chooseRole);
      console.log(this.attrId);
      // 进行提交保存属性和案例属性的关系
      let jsonParamArr = [];
      for(var i in this.chooseRole){
        jsonParamArr.push({
          "attrId": parseInt(this.attrId),
          "caseId": parseInt(this.chooseRole[i]),
          "weights": parseInt(i)+1
        })
      }
      deleteAndAddCaseAttrLink(jsonParamArr).then(res => {
        this.$message.success("保存成功");
      })

    },

     /**查询全部attr列表*/
    getAttrList() {
      this.loading = true;
      // 查询参数
      let queryParam = {
        pageNum: 1,
        pageSize: 10000
      };
      listAttr(queryParam).then(response => {
        this.attrListAll = response.rows;
        this.attrListAll = JSON.parse(JSON.stringify(this.attrListAll));
        this.loading = false;
        console.log(this.attrListAll);
      })
    },

    /**查询全部suppliercase列表from rds, 选择数据*/
    getCaseList() {
      this.loading  = true;
      listFromRds().then(
        response => {
        this.caseList = response.filter(x => x.authStatus == '1');
        console.log(this.caseList);
        
        this.loading = false;
      })
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleUploadSuccess(res, file) {
     // this.imageObjectUrl = URL.createObjectURL(file.raw);
      //this.uploadOnlineUrl = res.path;
     //
     
     console.log(res.urls);
      this.form.iconurl = res.data.url;
    },
    typeFormat(row, column, value) {
      //console.log('row', row);
      switch (value) {
        case "1":
          return '主属性';
        case "2":
          return '小属性';
        default:
          return '未知';
      }
    },
    statusFormat(row, column, value) {
      //console.log('row', row);
      switch (value) {
        case "1":
          return '启用';
        case "0":
          return '禁用';
        default:
          return '未知';
      }
    },

    /** 查询供应商案例属性列表 */
    getList() {
      this.loading = true;
      listAttr(this.queryParams).then(response => {
        this.attrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        subname: null,
        iconurl: null,
        status: "0",
        weights: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商案例属性";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAttr(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改供应商案例属性";
      });
    },

    // 点击 配置按钮操作, 弹出框显示, 读取当前选中的数据
    handleMapping(row) {
      
      this.subTitle = '配置[' + row. name + ']对应的供应商产品' ;
      this.attrId = row.id;

      let query = {
        pageNum: 1,
        pageSize: 10000,
        attrId: this.attrId
      };
     
      listCaseAttrLink(query).then(response => {
        let res = response.rows;
        let total = response.total;
        // 构造chooseRole数组
        this.chooseRole = res.map(x => x.caseId);
        this.openConfig = true;  
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAttr(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttr(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除供应商案例属性编号为"' + ids + '"的数据项？').then(function() {
        return delAttr(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supplier/attr/export', {
        ...this.queryParams
      }, `attr_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
   .edit_dev >>> .el-transfer-panel {
     width:270px;
   }
</style>